package CSnab::Controller::Index;

use strict;
use warnings;

use POSIX qw(strftime);
use HTML::Entities qw(encode_entities);
use MIME::Base64;
use MIME::Lite;
 
use CSnab::Decorate;
use CSnab::Model::Pager;

use base qw/CSnab::Controller/;

use constant {
	CSNAB_MENU => [
		{uid => 'index',    title => 'Главная',       class => 'but1', href => '/'},
		{uid => 'catalog',  title => 'Каталог',       class => 'but2', href => '/catalog/'},
		{uid => 'zavod',    title => 'Производители', class => 'but3', href => '/'},
		{uid => 'contacts', title => 'Контакты',      class => 'but7', href => '/contacts/'},
	],
	CABEL_ROOT_NODE_ID => 1,
};

sub dispatch {
	my $self   = shift;
	my $action = shift;
	my $ctx    = shift;
	
	my $uid = $ctx->param('uid') || 'undefined';
	
	$ctx->view->param(csnab_menu => CSNAB_MENU, curr_uid => $uid);
	
	$self->SUPER::dispatch($action, $ctx);
}

sub get_catalog {
	my $self = shift;
	my $ctx  = shift;
	
	my $root_node = $ctx->dbh->selectrow_hashref(q{
			select left_key, right_key, id
				from ns_tree
				where id=?
		}, undef, CABEL_ROOT_NODE_ID) || {};
	
	my $catalog = $ctx->dbh->selectall_arrayref(q{
			select id, catalog_id, title, level from ns_tree
				inner join catalog on content_id=catalog_id
				where left_key>? and right_key<?
				order by left_key;
		}, {Slice=>{}}, $root_node->{left_key}, $root_node->{right_key}) || [];
	
	my $tree;
	for my $item (@$catalog){
		if ($item->{level} == 2){
			push @$tree, $item;
		} else {
			push @{$tree->[-1]{catalog}}, $item;
			
			$tree->[-1]{count}++;
		}#end for
	}#end for
	
	return $tree;
}

sub index {
	my $self = shift;
	my $ctx  = shift;

	my @ids_center = qw(3 327 611    713 865 933   1120 1207 1229 1824 1882 1916);
	#my @ids_left   = qw(2090 2196 2219 2318 2422 2469);

	my %search  = map {$_, 1} @ids_center;
	my $catalog = $self->get_catalog($ctx);
	
	%search = map {$$_{catalog_id}, $_} grep exists $search{$$_{catalog_id}}, @$catalog;
	
	my $tree;
	
	for my $id (@ids_center){
		my $el = $search{$id};
		
		push @$tree, {id => $el->{id}, catalog_id => $el->{catalog_id}, title => $el->{title},
				count => $el->{count}, catalog => [@{$el->{catalog}}[0..4]]};
	}#end for
	
	CSnab::Decorate->construct(
			[qw/CSnab::Decorator::LinkUrl method link_razdel/]
		)->decorate_list($tree);
	
	$ctx->view->param(tree => $tree);
	
	$ctx->template('index.tmpl');
}

sub razdel {
	my $self = shift;
	my $ctx  = shift;
	
	my $id = $ctx->param('id');
	
	unless ($id){
		require CSnab::Controller::Error;
		CSnab::Controller::Error->throw_404($ctx);
		return;
	}#end unless
	
	my $catalog  = $self->get_catalog($ctx);
	
	my ($razdel) = grep $$_{id} == $id, @$catalog;

	CSnab::Decorate->construct(
			[qw/CSnab::Decorator::LinkUrl method link_razdel/]
		)->decorate($razdel);
	
	my $pager = new CSnab::Model::Pager(
			pager_width    => 9,
			items_per_page => $ctx->param('perpage') || 120,
			force          => 'id',
		);
	
	my $context = $pager->paginate(request => $ctx->getRequest, count => $razdel->{count});
	
	$razdel->{catalog} = [splice @{$razdel->{catalog}}, $context->{offset}, $context->{limit}]
		if $context->{total_pages} > 1;
	
	$ctx->view->param(tree => $razdel, pager => $context);
	
	$ctx->template('catalog/razdel.tmpl');
}

sub catalog {
	my $self = shift;
	my $ctx  = shift;
	
	my $catalog = $self->get_catalog($ctx);
	
	my $tree;
	
	for my $el (@$catalog){
		push @$tree, {id => $el->{id}, catalog_id => $el->{catalog_id},
			title => $el->{title}, count => $el->{count}};
	}#end for
	
	CSnab::Decorate->construct(
			[qw/CSnab::Decorator::LinkUrl method link_razdel/]
		)->decorate_list($tree);
	
	$ctx->view->param(catalog => $tree);
	
	$ctx->template('catalog/index.tmpl');
}

sub contacts {
	my $self = shift;
	my $ctx  = shift;
	
	$ctx->template('static/contacts.tmpl');
	
	my $req = $ctx->getRequest;
	
	return unless $req->method eq 'POST';
	
	my $now_time = strftime("%Y-%m-%d %H:%M:%S", localtime);
	
	my %params = map {$_, $req->param($_) || ''} qw/company_name phone inn email msg_comment/;
	
	my $feedback_email = $ctx->config->{feedback_email} or return;
		
	use utf8;

	for my $key (keys %params){	
		utf8::decode($params{$key});
		
		encode_entities($params{$key}, q{"'<>&});
	}#end for
	
	my $subject  = q{cabel-snab.ru - заявка от клиента!};
	my $msg_text =<<EOF;
Заявка от клиента [$now_time] !

Название компании  : "$params{company_name}"
Контактный телефон : "$params{phone}"
ИНН                : "$params{inn}"
E-mail             : "$params{email}"
Сообщение
$params{msg_comment}
EOF
		
	utf8::encode($subject);
	utf8::encode($msg_text);
		
    $subject = '=?utf-8?B?' . MIME::Base64::encode($subject, '') . '?=';

    my $msg = new MIME::Lite(
    		Type    => 'multipart/mixed',
    		From    => 'cabel-snab@robot.ru',
    		To      => $feedback_email,
    		#Cc      => ,
    		Subject => $subject,
		);
	
	$msg->attach(Type => 'text/plain; charset=utf-8', Data => $msg_text);
	
	$msg->send('smtp', $ctx->config->{smtp_server});
	
	$ctx->view->param(send_mail => 1);
}

1;
